<template>
  <div class="count">
    <!-- 修改进度弹窗 -->

    <el-dialog
      title="修改进度"
      :visible.sync="setqz"
      width="30%"
      v-loading="loadings1"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
    >
      <div class="schedule">
        <span style="margin-right: 16px">修改进度 : </span>
        <el-input-number
          v-model="getProcessRate"
          :step="5"
          size="mini"
          style="width: 75%"
        ></el-input-number>
      </div>
      <div class="illustrate" style="margin: 20px 0">
        <span style="margin-right: 20px; margin-left: 28px; float: left"
          >说明 :
        </span>
        <el-input
          ref="bt"
          style="width: 75%"
          type="textarea"
          :rows="2"
          placeholder="请输入说明内容"
          v-model="remark"
        >
        </el-input>
      </div>
      <div class="annex" style="margin: 20px 0">
        <span style="margin-right: 20px; margin-left: 28px; float: left"
          >附件 :
        </span>
        <el-upload
          class="upload-demo"
          multiple
          action="/seeyon/rest/attachment?applicationCategory=0&extensions=&firstSave=true?option.n_a_s=1"
          :on-change="handleChange"
          :on-success="handleAvatarSuccessful"
          :on-preview="showfile"
          ref="upload"
          :before-remove="beforeremove"
          :on-remove="Remove"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <div class="actualFinish" v-if="getProcessRate == 100">
        <span style="margin-right: 20px; margin-left: 28px; float: left;line-height:40px">实际完成时间 : </span>
        <el-date-picker v-model="actualFinishDate" type="date" placeholder="选择日期">
        </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取 消</el-button>
        <el-button type="primary" @click="xgjd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 任务回退弹窗 -->
    <el-dialog title="任务回退" :visible.sync="showRrollback" width="30%">
      <div class="illustrate" style="margin: 20px 0">
        <span style="margin-right: 20px; float: left">事由说明 : </span>
        <el-input
          style="width: 75%"
          type="textarea"
          :rows="2"
          placeholder="请输入事由说明内容"
          v-model="reason"
        >
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelRrollback">取 消</el-button>
        <el-button type="primary" @click="yesRrollback">确 定</el-button>
      </span>
    </el-dialog>

    <el-row class="flex-warp" type="flex">
      <!-- 左边任务树 -->
      <el-col :span="6">
        <div style="padding: 5px 20px; background: #01aaed">
          <h3 style="color: #f0f0f0">任务树</h3>
        </div>
        <div v-cloak>
          <div class="l_tree_container left-tree">
            <tree
              ref="rxTree"
              v-if="treeData.length > 0"
              :data="treeData"
              @on-children="handleTreeNode"
            ></tree>
          </div>
        </div>
      </el-col>
      <!-- 中间任务详情 -->
      <el-col :span="15">
        <div>
          <div
            class="PlanInfo"
            style="
              padding: 5px 20px;
              background: #01aaed;
              position: fixed;
              width: 61%;
              z-index: 100;
            "
          >
            <h3 style="color: #f0f0f0" @click="showdd">任务信息</h3>
          </div>
        </div>
        <div
          v-loading="loadings"
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading"
          class="countermsg"
          id="cdggw"
          style="
            border-right: 2px solid #eff1f6;
            height: 800px;
            border-left: 4px solid #eff1f6;
            white-space: nowrap;
            overflow-x: auto;
            margin-top: 40px;
            position: relative;
            padding-bottom: 50px;
          "
        >
          <div>
            <div style="position: absolute; top: 0px; right: 5px" id="jxxs">
              <!-- <el-tag :type="appStateTypeMethod(tip)" size="medium" effect="plain">{{tip}}</el-tag> -->
              <i
                :class="'iconfont ' + settaskstatus(basicInfo.state).type"
                style="font-size: 68px; color: red"
              ></i>
            </div>
            <taskmsg
              :publisher="publisher"
              :basic-info="basicInfo"
              :ext-info="extInfo"
              :ismodify="ismodify"
              :create="type == 'create' ? true : false"
            ></taskmsg>

            <el-collapse v-model="activeNames" @change="handleChange">
              <el-collapse-item id="xxxx" name="1">
                <template slot="title">
                  <i
                    class="iconfont icon-xiangxixinxi"
                    style="font-size: 28px; color: #c0a483"
                  ></i>
                  <p
                    style="
                      font-size: 16px;
                      margin-left: 5px;
                      font-weight: bolder;
                    "
                  >
                    详细信息
                  </p>
                </template>
                <div class="taskfrom" style="padding: 0px 25px">
                  <taskxxmsg
                    :type="type"
                    :ext-info.sync="extInfo"
                    :basic-info.sync="basicInfo"
                    :ismodify="ismodify"
                  ></taskxxmsg>
                </div>
              </el-collapse-item>
              <el-collapse-item id="xglc" name="2">
                <template slot="title">
                  <i
                    class="iconfont icon-tubiaozhizuomoban-"
                    style="font-size: 28px; color: #ff5000"
                  ></i>
                  <p
                    style="
                      font-size: 16px;
                      margin-left: 5px;
                      font-weight: bolder;
                    "
                  >
                    相关流程
                  </p>
                </template>
                <div class="add-template">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="addTemplate"
                    v-show="create || ((publisher || manager) && !completed)"
                    >添加模板
                  </el-button>
                </div>
                <rx-table
                  style="padding: 0 20px"
                  title="processes"
                  height="500px"
                  :tableData="tableData"
                  :isShowIndex="true"
                  :headers="processesHeader"
                  :isShowSelect="false"
                  :isOperation="true"
                  :loading="loading"
                  :isOperationAuth="true"
                  operWidth="230px"
                  :operations="processesOperation"
                  @on-click-operation="clickOperation"
                ></rx-table>
                <rx-dialog
                  v-if="showDialog"
                  :id="taskId"
                  :opType="type"
                  :key="refreshDialogKey"
                  :dialogVisible="dialogVisible"
                  :tableData="templateData"
                  :operationStatus="operationStatus"
                  :templateId="templateId"
                  @close-dialog="closeDialog"
                  @close-dialog-table="closeDialogTable"
                ></rx-dialog>
                <template>
                  <!--<rx-proce-detail
                                            v-if="taskProceShowDialog"
                                            :taskProceDialogVisible="taskProceDialogVisible"
                                            :processesUrl="processesUrl"
                                            @handle-close-dialog="handleCloseDialog"
                                    ></rx-proce-detail>-->
                  <el-dialog
                    :title="templateTitle"
                    :visible.sync="taskProceDialogVisible"
                    width="1400px"
                    @close="handleCloseDialog"
                  >
                    <rx-proce-detail
                      :isSend="isSend"
                      :proUrl="proUrl"
                    ></rx-proce-detail>
                  </el-dialog>
                </template>
                <template>
                  <el-dialog
                    title="修改权重"
                    :visible.sync="updateWeightDialogVisible"
                    width="400px"
                  >
                    <rx-form
                      v-if="updateWeightDialogVisible"
                      :data="formData"
                      @close-dialog-process-form="closeDialogProcessForm"
                      @click-save-form="saveWeight"
                    ></rx-form>
                  </el-dialog>
                </template>
              </el-collapse-item>
              <el-collapse-item
                id="zrw"
                name="3"
                v-if="!ismodify"
                style=""
              >
                <template slot="title">
                  <i
                    class="iconfont icon-zirenwu"
                    style="font-size: 28px; color: #d4237a"
                  ></i>
                  <p
                    style="
                      font-size: 16px;
                      margin-left: 5px;
                      font-weight: bolder;
                    "
                  >
                    子任务
                  </p>
                </template>
                <div class="add-template">
                  <el-button
                    v-if="isBtnAuth"
                    type="primary"
                    size="mini"
                    @click="addSubTask"
                    >添加子任务
                  </el-button>
                  <span style="color: red" v-else-if="completed"
                    >当前任务已完成，无法添加子任务</span
                  >
                  <span style="color: red" v-else
                    >任务未保存或没有新建子任务权限</span
                  >
                </div>
                <!-- 隐藏表格 -->
                <!-- <rx-table
                  style="padding: 0 20px"
                  title="subTask"
                  height="400px"
                  :loading="loading"
                  :tableData="subTaskData"
                  :isShowIndex="true"
                  :headers="subTaskHeader"
                  :isShowSelect="false"
                  :isOperation="true"
                  operWidth="120px"
                  :operations="subTaskOperation"
                  @on-click-operation="clickOperation"
                ></rx-table> -->
              </el-collapse-item>
              <!-- 进度汇总 -->
              <el-collapse-item
                id="jdhz"
                name="5"
                v-if="!ismodify && basicInfo.taskLevel == '1'"
              >
                <template slot="title">
                  <i
                    class="iconfont icon-zirenwu"
                    style="font-size: 28px; color: #d4237a"
                  ></i>
                  <p
                    style="
                      font-size: 16px;
                      margin-left: 5px;
                      font-weight: bolder;
                    "
                  >
                    进度汇总
                  </p>
                </template>
                <div class="export-template">
                  <el-button
                    v-if="isExport"
                    type="primary"
                    size="mini"
                    @click="exportEvt"
                    >导出
                  </el-button>
                </div>
                <rx-table
                  style="padding: 0 20px"
                  title="summary"
                  height="400px"
                  :loading="loading"
                  :tableData="summaryData"
                  :isShowIndex="true"
                  :headers="scheduleHeader"
                  :isShowSelect="false"
                  :isOperation="false"
                  :isView="false"
                  operWidth="120px"
                  @on-click-operation="clickOperation"
                ></rx-table>
              </el-collapse-item>
              <el-collapse-item v-if="isReply" id="gtjl" name="4">
                <template slot="title">
                  <i
                    class="iconfont icon-huifu"
                    style="font-size: 28px; color: #f4ea2a"
                  ></i>
                  <p
                    style="
                      font-size: 16px;
                      margin-left: 5px;
                      font-weight: bolder;
                    "
                  >
                    任务记录
                  </p>
                </template>
                <template>
                  <LinkUpRecord
                    ref="rxRecord"
                    :basicData="basicInfo"
                    :id="taskId"
                  ></LinkUpRecord>
                </template>
              </el-collapse-item>
            </el-collapse>
          </div>

          <div
            style="
              text-align: center;
              position: fixed;
              width: 61.7%;
              bottom: 0px;
              background-color: white;
              padding: 10px 0;
              z-index: 200;
              background: #fafafa;
            "
          >
            <el-button
              round
              size="mini"
              v-if="
                (!ismodify &&
                  basicInfo.taskSubmissionStatus == '已接收' &&
                  !closed &&
                  (publisher || manager) &&
                  (!completed ||
                    (completed &&
                      basicInfo.cycle &&
                      basicInfo.sourceTaskId === basicInfo.taskId))) ||
                (!ismodify && basicInfo.approveState == '草稿')
              "
              @click="clickModify"
            >
              编辑
            </el-button>
            <el-button
              @click="saveTask(1, -1)"
              type="success"
              round
              size="mini"
              v-if="
                ismodify &&
                (publisher || manager) &&
                (!completed ||
                  (completed &&
                    basicInfo.cycle &&
                    basicInfo.sourceTaskId === basicInfo.taskId))
              "
              >发布
            </el-button>
            <!-- <el-button
              @click="hhh"
              type="success"
              round
              size="mini"
              >打印测试数据
            </el-button> -->
            <el-button
              round
              size="mini"
              @click="saveTask(0, -1)"
              type="primary"
              v-if="
                (draft || type == 'create') &&
                ismodify &&
                (publisher || manager) &&
                !completed
              "
            >
              保存草稿
            </el-button>
            <el-button
              round
              size="mini"
              @click="xgjdd"
              type="info"
              v-if="
                !draft &&
                basicInfo.taskSubmissionStatus == '已接收' &&
                !closed &&
                !ismodify &&
                (publisher || manager || joiner) &&
                !completed
              "
              >修改进度
            </el-button>
            <el-button
              round
              size="mini"
              @click="saveTask(0, 3)"
              v-if="canApplyApprove && !ismodify"
              >提交审批</el-button
            >
            <el-button
              round
              size="mini"
              @click="closetask"
              type="danger"
              v-if="!draft && publisher && !closed && !completed && !ismodify"
              >删除任务
            </el-button>
            <el-button
              round
              size="mini"
              @click="saveTask(0, 11)"
              type="danger"
              v-if="publisher && basicInfo.cycle && !ismodify"
              >停止周期任务
            </el-button>
            <el-button
              round
              size="mini"
              @click="retask"
              type="info"
              v-if="!draft && publisher && closed && !completed"
              >恢复任务
            </el-button>
            <el-button
              type="warning"
              round
              size="mini"
              @click="saveTask(0, 4)"
              v-if="canApprove && !ismodify"
              >审批通过
            </el-button>
            <el-button
              type="danger"
              round
              size="mini"
              @click="saveTask(0, 6)"
              v-if="canApprove && !ismodify"
              >审批驳回
            </el-button>
            <el-button
              type="danger"
              round
              size="mini"
              @click="taskBack"
              v-if="
                basicInfo.taskSubmissionStatus &&
                basicInfo.taskSubmissionStatus == '未操作' &&
                !ismodify &&
                basicInfo.approveState !== '草稿'
              "
              >任务回退
            </el-button>
            <el-button
              type="success"
              round
              size="mini"
              @click="taskReception"
              v-if="
                basicInfo.taskSubmissionStatus &&
                basicInfo.taskSubmissionStatus == '未操作' &&
                !ismodify &&
                basicInfo.approveState !== '草稿'
              "
              >任务接收
            </el-button>
          </div>
        </div>
      </el-col>
      <!-- 右侧目录 -->
      <el-col :span="3">
        <div class="PlanInfo" style="padding: 5px 20px; background: #01aaed">
          <h3 style="color: #f0f0f0">目录</h3>
        </div>
        <div class="l_tree_container">
          <anchor-point
            ref="tree"
            v-if="isPointData"
            :data="treeConfig.anchorPointData"
            @on-children="onChangeTreeChildren"
          ></anchor-point>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Editor from "../../components/editor/editor";
import { taskinfo } from "../../mixins/taskinfo";
import Tree from "@/components/tree/tree";
import AnchorPoint from "@/components/tree/anchorPoint";
import RxTable from "@/components/table/RxTable";
import RxDialog from "@/components/RxDialog";
import d from "../../utils/url";
import taskmsg from "../../components/taskfrom/taskmsg";
import taskxxmsg from "../../components/taskfrom/taskxxmsg";
import LinkUpRecord from "../task-info/linkUpRecord";
import { deepClone } from "../../utils";
import RxProceDetail from "./RxProceDetail";
import RxForm from "../../components/RxForm";
import url from "../../utils/url";
import axios from "axios";
var ddt;

export default {
  mixins: [taskinfo],
  name: "default",
  data() {
    return {
      // // 进度汇总数据
      // summaryData:[],
      reason: "",
      showRrollback: false, //任务回退说明弹窗控制
      objd: {},
      treeData: [], //树形结构
      activeNames: ["1","3","4"],
      tableData: [],
      templateData: [],
      showDialog: false,
      dialogVisible: false, //是否显示弹窗
      refreshDialogKey: 0,
      treeKey: 0,
      operationStatus: "add",
      templateId: "", //编辑状态下右边列表显示
      subTaskData: [],
      loading: true,
      taskProceDialogVisible: false, //任务流程查看打开 iframe
      taskProceShowDialog: false,
      proUrl: "", //流程url
      isPointData: false,
      superId: "",
      isSend: false,
      templateTitle: "",
      updateWeightDialogVisible: false, //修改权重弹窗
      formData: {},
    };
  },
  components: {
    RxForm,
    RxProceDetail,
    Tree,
    AnchorPoint,
    Editor,
    RxTable,
    RxDialog,
    taskmsg,
    taskxxmsg,
    LinkUpRecord,
  },
  created() {
    ddt = this.objd;
    this.init();
    this.windFunction();
    this.getid();
  },
  mounted() {},
  watch: {
    basicInfo: {
      handler() {
        if (this.basicInfo.taskLevel !== "1") {
          this.treeConfig = {
            anchorPointData: [
              {
                name: "目录",
                id: "1",
                show: true,
                children: [
                  {
                    name: "基础信息",
                    id: "2",
                    children: [],
                    show: true,
                  },
                  {
                    name: "详细信息",
                    id: "3",
                    children: [],
                    show: true,
                  },
                  {
                    name: "相关流程",
                    id: "4",
                    children: [],
                    show: true,
                  },
                  {
                    name: "子任务",
                    id: "5",
                    children: [],
                    show: true,
                  },
                  {
                    name: "进度汇总",
                    id: "6",
                    children: [],
                    show: true,
                  },
                  {
                    name: "任务记录",
                    id: "7",
                    children: [],
                    show: true,
                  },
                ],
              },
            ],
            taskTreeLine: 0, //实线
            anchorPointLine: 1, //虚线
          };
        }
      },
      deep: true,
      immediate: true,
    },
    remark: {
      handler(newVal, oldVal) {
        if (newVal !== "") {
          this.$refs["bt"].$el.children[0].style.background = "white";
        } else {
          this.$refs["bt"].$el.children[0].style.background = "#feefcf";
        }
      },
      deep: true,
    },
    setqz: {
      handler(newVal, oldVal) {
        if (newVal == false) {
          this.fileList = [];
          this.setqz = false;
          this.remark = "";
        }
      },
      immediate: true,
    },
  },

  methods: {
    // // 获取进度汇总数据
    // getSummaryData(){
    //    axios.get(`/seeyon/rest/bhtTask/getSubTask/${this.basicInfo.taskId}`).then((res)=>{
    //     console.log('任务汇总接口调试',res)
    //     if(res.data.code == 200){
    //       this.summaryData = res.data.data
    //     }
    //   })
    // },
    // 进度汇总导出
    exportEvt() {
      window.open(
        `/seeyon/originalDataImport.do?method=getExcel&taskId=${this.basicInfo.taskId}&taskName=${this.basicInfo.title}`,
        "_self"
      );
    },
    handleAvatarSuccessful(res, file) {
      res.atts.forEach((item) => {
        this.fileUrl.push(item.fileUrl);
      });
    },
    // 取消任务回退
    cancelRrollback() {
      this.showRrollback = false;
    },
    // 确定任务回退
    yesRrollback() {
      this.loadings = true;
      axios
        .post(`/seeyon/rest/bhtTask/taskRollback`, {
          taskId: this.basicInfo.taskId,
          content: this.reason,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.loadings = false;
            // 页面刷新
            window.location.reload();
          }
        });
      this.showRrollback = false;
    },
    // 任务回退按钮点击
    taskBack() {
      this.showRrollback = true;
    },
    // 触发添加子任务方法
    handleCustomEvent() {
      // 在这里处理子组件触发的事件
      this.addSubTask()
    },
    // 任务接收按钮点击
    taskReception() {
      this.loadings = true;
      axios
        .post(`/seeyon/rest/bhtTask/taskReceive`, {
          taskId: this.basicInfo.taskId,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.loadings = true;
            // 页面刷新
            window.location.reload();
          }
        });
    },
    // 取消进度修改
    cancelUpload() {
      this.fileList = [];
      this.setqz = false;
      this.remark = "";
      // this.fileUrl.forEach((item)=>{
      //   this.$http
      //   .query(`/seeyon/rest/taskDetail/attachments/delete/${item}`)
      //   .then((res) => {
      //     let { code, data } = res;
      //     if (code == 0) {
      //       if (file.response) {
      //         file = file.response.atts[0];
      //       }
      //       _this.$message({
      //         type: "success",
      //         message: "删除成功!",
      //       });
      //     } else {
      //       this.$message({
      //         type: "info",
      //         message: "删除失败!",
      //       });
      //     }
      //   });
      // })
      this.fileUrl = [];
    },
    Remove(file, fileList) {
      let _this = this;
      // if (file.response){
      //     file = file.response.atts[0]
      // }
      // _this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      // });
      this.$http
        .query(
          `/seeyon/rest/taskDetail/attachments/delete/${file.response.atts[0].fileUrl}`
        )
        .then((res) => {
          let { code, data } = res;
          if (code == 0) {
            if (file.response) {
              file = file.response.atts[0];
            }
            _this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message({
              type: "info",
              message: "删除失败!",
            });
          }
        });
    },
    xgjdd() {
      this.getProcessRate = this.basicInfo.processRate * 100;
      this.setqz = true;
    },
    init() {
      this.taskId = d.getParams("taskId");
      this.type = d.getParams("type");
      this.initData(this.taskId);
      this.isReply = this.type == "create" ? false : true;
    },

    async initData(taskId) {
      this.taskId = taskId;
      await this.initTreeNode();
      //初始化不显示沟通记录
      this.showPointTree(this.type);
      if (this.type == "create") {
        //如果一进来是根节点是没有superId 默认展开第一级 type是create 默认高亮 '新建任务'
        let superId = d.getParams("superId");
        if (superId) {
          this.pointTreeNodeOrSetColor(superId, "-1");
        } else {
          this.setTreeNodeShow(this.treeData, taskId);
          let node = this.getTreeNodeByTaskId(this.treeData, "-1");
          this.$nextTick(() => {
            this.$refs["rxTree"].setNodeColor(node);
          });
          this.treeData = deepClone(this.treeData);
        }
      } else {
        /*  let node = this.getTreeNodeByTaskId(this.treeData, this.taskId)
                      this.$nextTick(() => {
                          this.$refs['rxTree'].setNodeColor(node)
                      })*/
        this.pointTreeNodeOrSetColor(d.getParams("superId"), taskId);
        // this.getSummaryData()
        // console.log('this.summaryDat',this.summaryData)
      }
    },
    //加载右边树
    showPointTree(type) {
      this.isPointData = false;
      let pointData = this.treeConfig.anchorPointData[0].children;
      for (let i = 0; i < pointData.length; i++) {
        if (pointData[i].id == "6") {
          type == "create"
            ? (pointData[i].show = false)
            : (pointData[i].show = true);
        }
      }
      this.treeConfig.anchorPointData = deepClone(
        this.treeConfig.anchorPointData
      );
      this.isPointData = true;
    },

    getEditorData(val) {
      this.editorData = val;
    },
    //树
    async initTreeNode() {
      this.treeData = [];
      let url =
        this.type == "create"
          ? `/seeyon/rest/taskDetail/taskTree/-1/${this.taskId}`
          : `/seeyon/rest/taskDetail/taskTree/${this.taskId}/-1`;
      let res = await this.$http.query(url);
      this.treeData.push(res.data);
    },
    //刷新表单数据
    handleTreeNode(item) {
      if (item.basicInfo.taskId == this.taskId) {
        return;
      }
      if (!this.ismodify) {
        this.taskId = item.basicInfo.taskId;
        this.loading = true;
        this.loadDataByNodeTaskId(item);
      } else {
        this.$confirm("当前任务还未保存！是否离开?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.loading = true;
            if (this.type == "create") {
              this.delProcData(this.taskId);
            }
            this.taskId = item.basicInfo.taskId;
            this.loadDataByNodeTaskId(item);
          })
          .catch(() => {
            this.loading = false;
            let node = this.getTreeNodeByTaskId(this.treeData, this.taskId);
            this.$nextTick(() => {
              this.$refs["rxTree"].setNodeColor(node);
            });
            let prentNode = this.getTreeNodeByTaskId(
              this.treeData,
              item.basicInfo.taskId
            );
            this.$nextTick(() => {
              this.$refs["rxTree"].removeNodeColor(prentNode);
            });
          });
      }
    },

    //删除流程
    delProcData(taskId) {
      this.$http.query(`/seeyon/rest/taskDetail/leave/${taskId}`).then(() => {
        this.loadProcessData(this.taskId);
      });
    },

    loadDataByNodeTaskId(item) {
      this.superId = item.basicInfo.superId;
      this.taskProceShowDialog = true;
      this.loadings = true;
      this.type = "view";
      this.showPointTree(this.type); //右边树
      this.removeTreeNodeByTaskId(this.treeData, "-1");
      this.getid(item.basicInfo.taskId);
      if (this.isReply) {
        this.$refs["rxRecord"].loadReply();
        this.$refs["rxRecord"].loadLog();
      }
    },

    //获取树形节点
    onChangeTreeChildren(item) {
      if (item.id == 2) {
        document.getElementById("jxxs").scrollIntoView();
      } else {
        this.activeNames.push(item.id - 2);
        if (item.id - 2 == 1) {
          document.getElementById("xxxx").scrollIntoView();
        } else if (item.id - 2 == 2) {
          document.getElementById("xglc").scrollIntoView();
        } else if (item.id - 2 == 3) {
          document.getElementById("zrw").scrollIntoView();
        } else if (item.id - 2 == 4) {
          document.getElementById("gtjl").scrollIntoView();
        }
      }
    },

    //加载流程列表数据
    loadProcessData(taskId) {
      this.$http
        .query(`/seeyon/rest/taskDetail/process/${taskId}`)
        .then((res) => {
          let { code, data } = res;
          if (code == 0) {
            for (let i = 0; i < data.length; i++) {
              data[i].colWeight = Number(data[i].colWeight).toFixed(2);
            }
            this.tableData = data;
            if (this.tableData.length > 0) {
              // this.activeNames.push("2");
            } else {
              for (let i = 0; i < this.activeNames.length; i++) {
                if (this.activeNames[i] == "2") {
                  this.activeNames.splice(i, 1);
                }
              }
            }
            this.initOperations(this.tableData);
          }
          this.loading = false;
        });
    },
    //添加模板弹窗
    addTemplate() {
      this.dialogVisible = true;
      this.loadProcessesData();
    },
    //快捷发起弹窗
    quickLaunch() {
      console.log(this.tableData);
    },
    //加载模板列表数据
    async loadProcessesData() {
      let res = await this.$http.query("/seeyon/rest/taskDetail/tree/template");
      let { code, data } = res;
      if (code == 0) {
        this.templateData = data;
        this.showDialog = true;
      }
    },

    //加载子任务列表数据
    loadSubTask(taskId) {
      this.$http
        .query(`/seeyon/rest/bhtTask/allChildren/${taskId}/0?subCategory=-1`)
        .then((res) => {
          let { code, data } = res;
          let tempData = [];
          if (code == 0) {
            if (data) {
              for (let i = 0; i < data.length; i++) {
                let temp = data[i].basicInfo;
                temp.stateColor = this.handleSubTaskStatusColor(temp.state);
                temp.taskDate = temp.startDate + " - " + temp.endTime;
                temp.processRate = (Number(temp.processRate) * 100).toFixed(0);
                tempData.push(temp);
              }
              this.subTaskData = tempData;
              if (this.subTaskData.length > 0) {
                this.activeNames.push("3");
              } else {
                for (let i = 0; i < this.activeNames.length; i++) {
                  if (this.activeNames[i] == "3") {
                    this.activeNames.splice(i, 1);
                  }
                }
              }
            }
          }
          this.loading = false;
        });
    },
    appStateTypeMethod(appState) {
      //正常、完成待审、正常完成、超期完成、被驳回、已关闭
      let type = "success";
      switch (appState) {
        case "正常":
        case "正常完成":
          type = "success";
          break;
        case "超期完成":
          type = "danger";
          break;
        case "被驳回":
        case "完成待审":
          type = "warning";
          break;
        case "已关闭":
          type = "info";
          break;
        default:
          type = "";
          break;
      }
      return type;
    },
    handleSubTaskStatusColor(state) {
      let color = "";
      switch (state) {
        case "进行中":
          color = "#40E0D0";
          break;
        case "已完成":
          color = "#00FA9A";
          break;
        case "已超期":
          color = "#FF0000";
          break;
        case "已关闭":
          color = "#000";
          break;
        case "未开始":
          color = "#BEBEBE";
          break;
        case "预警中":
          color = "#EEAD0E";
          break;
        default:
          color = "#000";
          break;
      }
      return color;
    },

    //添加子任务
    addSubTask() {
      if (this.type == "create") {
        this.$message.warning("当前任务还未保存，无法新增子任务！");
      } else {
        this.$set(this, "ismodify", true);
        //当保存成功后 继续添加任务 将type状态改成 create
        this.type = "create";
        this.isReply = false;
        this.subTaskData = [];
        // 保存父任务内容
        window.sessionStorage.setItem('parentTitle',this.basicInfo.title)
        window.sessionStorage.setItem('parentRichContent',this.basicInfo.richContent)
        window.sessionStorage.setItem('parentTime',this.basicInfo.time)
        window.sessionStorage.setItem('reportCycle',this.extInfo.reportCycle)
        window.sessionStorage.setItem('warnDay',this.basicInfo.warnDay)
        this.showPointTree(this.type);
        this.getid(this.taskId);
        //type==create 状态下添加当前新建任务节点
        let data = this.setTreeNodeByTaskId(this.treeData, this.taskId);
        this.setTreeNodeShow(this.treeData, this.taskId);
        this.treeData = deepClone(data);
        let node = this.getTreeNodeByTaskId(this.treeData, "-1");
        this.$nextTick(() => {
          this.$refs["rxTree"].setNodeColor(node);
        });

        let prentNode = this.getTreeNodeByTaskId(this.treeData, this.taskId);
        this.$nextTick(() => {
          this.$refs["rxTree"].removeNodeColor(prentNode);
        });
      }
    },

    //列表操作事件
    clickOperation(row, index, key, type) {
      if (index == 0) {
        if (type == "subTask") {
          if (!this.ismodify) {
            this.pointTreeNodeOrSetColor(row.superId, row.taskId);
            this.$refs["rxTree"].defaultStyle();
            let item = {
              basicInfo: row,
            };
            this.loadDataByNodeTaskId(item);
          } else {
            this.$confirm("当前任务还未保存！是否离开?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.pointTreeNodeOrSetColor(row.superId, row.taskId);
                this.$refs["rxTree"].defaultStyle();
                let item = {
                  basicInfo: row,
                };
                this.loadDataByNodeTaskId(item);
              })
              .catch(() => {});
          }
        } else {
          //发起
          this.isSend = false;
          let url = "";
          if (row.col) {
            this.templateTitle = "发起流程";
            url = row.urls.send;
          } else {
            this.templateTitle = "添加";
            url = row.urls.create;
          }
          let param = {
            url: url,
          };
          this.proUrl = param;
          if (this.isBtnAuth) {
            window.open(this.proUrl.url);
          } else {
            this.$message({
              type: "error",
              message: "您没有发起流程的权限!",
            });
          }
          // this.taskProceDialogVisible = true;
        }
      } else if (index == 1) {
        if (type == "subTask") {
          //删除子任务
          console.log("操作权限:" + this.isBtnAuth);
          if (this.isBtnAuth) {
            this.$confirm("确认将该任务及其子任务移动至回收站?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.$http
                  .post("/seeyon/rest/taskDetail/modify/7", {
                    taskId: row.taskId,
                  })
                  .then(() => {
                    this.loadSubTask(this.taskId);
                  });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              });
          } else {
            this.$message({
              type: "error",
              message: "您没有删除该任务的权限!",
            });
          }
        } else {
          //操作任务流程查看
          // this.taskProceDialogVisible = true;
          this.templateTitle = "查看模板";
          let param;

          if (row.col) {
            this.isSend = true;
            param = {
              form: row.urls.template.form,
              instruction: row.urls.template.instruction,
              workflow: row.urls.template.workflow,
            };
          } else {
            this.isSend = false;
            param = {
              url: row.urls.browse,
            };
          }
          this.proUrl = param;
          this.proUrl.isSend = this.isSend;
          window.objd = this.proUrl;
          // window.open(`/cs.html`)
          window.open("/seeyon/task/cs.html");
        }
      } else if (index == 2) {
        this.templateTitle = "查看流程";
        this.isSend = false;

        if (row.col && row.dataId) {
          let param = {
            url: row.urls.view,
          };
          this.proUrl = param;
        }
        // this.taskProceDialogVisible = true;
        window.open(this.proUrl.url);
      } else if (index == 3) {
      } else if (index == 4) {
        if (key == "updateWeight") {
          if (this.isBtnAuth) {
            this.updateWeightDialogVisible = true;
            this.formData = row;
          } else {
            this.$message({
              type: "error",
              message: "您没有修改权重的权限!",
            });
          }
        }
        /*if (row.col) {
                        //修改
                        this.showDialog = false;
                        this.loadProcessesData();
                        this.operationStatus = 'edit'
                        this.templateId = row.templateId;
                        this.dialogVisible = true;
                    } else {
                        this.taskProceDialogVisible = true;
                        this.templateTitle = '编辑'
                        this.isSend = false;
                        let param = {
                            url: row.urls.update,
                        }
                        this.proUrl = param
                    }*/
      } else if (index == 5) {
        if (this.isBtnAuth) {
          if (key == "updateWeight") {
            this.updateWeightDialogVisible = true;
            this.formData = row;
          } else {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.$http
                  .post(`/seeyon/rest/taskDetail/process/delete/${row.id}`)
                  .then((res) => {
                    if (res.code == 0) {
                      this.$message.success("删除成功！");
                      this.loadProcessData(this.taskId);
                    }
                  });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              });
          }
        } else {
          this.$message({
            type: "error",
            message: "您没有相关操作权限!",
          });
        }
      }
    },

    //保存成功后刷新树
    async refreshTreeNode(pid) {
      this.treeData = [];
      //异步从新加载树节点
      await this.initTreeNode();
      //定位当前添加后的node 并高亮
      this.pointTreeNodeOrSetColor(pid, this.taskId);
    },

    //定位当前添加后的node 并高亮
    pointTreeNodeOrSetColor(pid, taskId) {
      let nodes = this.getTreeParentId(this.treeData, pid);
      if (!nodes) return;
      for (let i = 0; i < nodes.length; i++) {
        this.setTreeNodeShow(this.treeData, nodes[i].basicInfo.taskId);
      }

      this.treeData = deepClone(this.treeData);
      let node = this.getTreeNodeByTaskId(this.treeData, taskId);
      this.$nextTick(() => {
        this.$refs["rxTree"].setNodeColor(node);
      });
    },

    //获取当前子节点以上所有父级节点
    getTreeParentId(list, pid) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].basicInfo.taskId == pid) {
          return [list[i]];
        }
        if (list[i].children) {
          let node = this.getTreeParentId(list[i].children, pid);
          if (node) {
            return node.concat(list[i]);
          }
        }
      }
    },

    //将当前自己show设置为true
    setTreeNodeShow(data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length > 0) {
          if (data[i].basicInfo.taskId == id) {
            data[i].show = true;
          }
          this.setTreeNodeShow(data[i].children, id);
        }
      }
      return data;
    },

    //根据当前taskId 找出node节点
    getTreeNodeByTaskId(data, tid) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children) {
          if (data[i].basicInfo.taskId == tid) {
            return data[i];
          } else {
            //得到当前节点 退出
            let node = this.getTreeNodeByTaskId(data[i].children, tid);
            if (node) {
              return node;
            }
          }
        }
      }
    },

    //修改当前节点
    updateTreeNode(data, id, title) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].basicInfo.taskId == id) {
          data[i].basicInfo.title = title;
        }
        this.updateTreeNode(data[i].children, id, title);
      }
      return data;
    },

    //移除新建任务节点
    removeTreeNodeByTaskId(data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].basicInfo.taskId == id) {
          data.splice(i, 1);
          return;
        }
        this.removeTreeNodeByTaskId(data[i].children, id);
      }
      return data;
    },

    //当前节点下添加新建任务节点
    setTreeNodeByTaskId(data, tId) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].basicInfo.taskId == tId) {
          let params = {
            basicInfo: {
              taskId: "-1",
              superId: data[i].basicInfo.taskId,
              title: "当前新建任务",
            },
            children: [],
          };
          data[i].children.push(params);
          return data;
        }
        this.setTreeNodeByTaskId(data[i].children, tId);
      }
      return data;
    },

    handleChange(val) {
      return false;
    },
    showfile(file) {
      console.log("下载附件");
      if (file.response) {
        file = file.response.atts[0];
      }

      if (file.mimeType.slice(0, 5) == "image") {
        this.imgPath = "#";
        this.imgPath = `/seeyon/fileUpload.do?method=showRTE&fileId=${encodeURI(
          file.fileUrl
        )}&type=image&showType=big`;
        this.imgfile = file;
        this.dialogVisible = true;
      } else if (file.mimeType == "application/pdf") {
        window.open(
          encodeURI(
            `/seeyon/fileDownload.do?method=doDownload4Office&type=Pdf&isOpenFile=true&fileId=${encodeURI(
              file.fileUrl
            )}&createDate=${file.createdate.slice(0, 10)}&filename=${encodeURI(
              file.filename
            )}`
          )
        );
      } else {
        window.location.href = encodeURI(
          `/seeyon/rest/attachment/file/${encodeURI(
            file.fileUrl
          )}?fileName=${encodeURI(file.filename)}`
        );
      }
    },

    beforeremove(file) {
      return this.$confirm(`确定移除该文件 ${file.name}？`);
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    //设置任务状态
    settaskstatus(n) {
      let obj = {
        type: "icon-yiguanbi",
        color: "red",
      };
      switch (n) {
        case "正常":
        case "已关闭":
          obj.type = "icon-yiguanbi";
          break;
        case "进行中":
          obj.type = "icon-jinhangzhong";
          break;
        case "已完成":
          obj.type = "icon-yiwancheng";
          break;
        case "已超期":
          obj.type = "icon-yichaoqi1";
          break;
        case "预警中":
          obj.type = "icon-yujingzhong";
          break;
        case "未开始":
          obj.type = "icon-weikaishi1";
          break;
        default:
          obj.type = "";
          break;
      }
      return obj;
    },
    //流程按钮操作
    initOperations(data) {
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < this.processesOperation.length; j++) {
          let btn = {
            send: true,
            detail: true,
            detailPrco: false,
            update: true,
            delete: true,
            updateWeight: true,
          };
          if (data[i].col) {
            btn.update = false;
            if (data[i].dataId) {
              if (this.processesOperation[j].key == "send") {
                btn.send = false;
                btn.delete = false;
                btn.detailPrco = true;
                data[i].operation = btn;
              }
            } else {
              this.type == "create" ? (btn.send = false) : (btn.send = true);
              btn.delete = true;
              btn.detail = true;
              data[i].operation = btn;
            }
          } else {
            if (!data[i].col) {
              btn.send = false;
              btn.detail = true;
              btn.update = true;
              if (data[i].dataId) {
                btn.delete = false;
              } else {
                btn.send = true;
                btn.delete = true;
                btn.detail = false;
                btn.update = false;
              }
            }
            data[i].operation = btn;
          }
          if (this.basicInfo.taskLevel == this.basicInfo.maxLevel) {
            data[i].operation.send = true;
          }
        }
      }
      this.tableData = deepClone(data);
    },
    //修改权重
    saveWeight(data) {
      let params = {
        data: [],
        taskId: this.taskId,
      };
      params.data.push(data);
      this.$http
        .post(`/seeyon/rest/taskDetail/process/updateBatch`, params)
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("修改成功！");
            this.updateWeightDialogVisible = false;
            this.loadProcessData(this.taskId);
          }
        });
    },

    //关闭修改权重弹窗
    closeDialogProcessForm() {
      this.updateWeightDialogVisible = false;
    },

    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      //从新渲染组件
      this.refreshDialogKey += 1;
    },
    //关闭流程子任务弹窗
    closeDialogTable() {
      this.showDialog = false;
      this.loadProcessData(this.taskId);
    },
    handleCloseDialog() {
      this.taskProceDialogVisible = false;
    },

    clickModify() {
      this.ismodify = !this.ismodify;
      console.log("this.ismodify", this.ismodify);
      this.isSave = false;
    },

    //发起流程关闭窗口
    windFunction() {
      let _this = this;
      window.closeTaskProcePage = function (val) {
        _this.loadProcessData(_this.taskId);
        _this.taskProceDialogVisible = false;
      };
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/icon.css";
/*icon*/
[v-cloak] {
  display: none;
}
/deep/.illustrate .el-textarea > textarea {
  background-color: #feefcf;
}
.iconfont {
  color: #409eff;
  font-size: 16px;
  margin-right: 10px;
}

/* ****************************树*****************************/

.left-tree {
  width: 100%;
  padding-bottom: 20px;
  overflow: hidden;
  overflow: auto;
}
.l_tree_container {
  position: relative;
  left: -20px;
}

.l_tree_container > .l_tree::before,
.l_tree_container > .l_tree > .l_tree_branch::after {
  display: none;
}

/* *********************************************************/

.countermsg::-webkit-scrollbar {
  width: 4px;
  height: 10px;
  /**/
}

.countermsg::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}

.countermsg::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}

.countermsg::-webkit-scrollbar-thumb:hover {
  background: #333;
}

.countermsg::-webkit-scrollbar-corner {
  background: #179a16;
}

.add-template,
.export-template {
  min-width: 200px;
  height: 40px;
  margin-left: 20px;
}

.taskfrom {
  margin-top: 5px;
}

.countermsg /deep/ .el-collapse-item__header {
  padding: 0 20px;
  font-size: 16px;
}

.formitems {
  margin-top: 20px;
}

.count /deep/ .el-dialog__header {
  background-color: white;
}

.itemtle {
  color: #999999;
  font-size: 15px;
}

.taskicon {
  margin-right: 15px;
}

/*.taskfrom /deep/ .el-input__inner {*/
/*    padding: 0 15px;*/
/*    !*width: 85%*!*/
/*}*/

/*.taskfrom /deep/ .el-input-number--mini {*/
/*    line-height: 28px;*/
/*}*/

/*.taskfrom /deep/ .el-input-number--mini .el-input-number__increase {*/
/*    width: 28px;*/
/*    font-size: 12px;*/
/*    !*right: 20px;*!*/
/*    !*height: 26px;*!*/
/*}*/

/*.taskfrom /deep/ .el-input-number--mini .el-input-number__decrease {*/

/*    height: 26px;*/
/*}*/

/*.taskfrom /deep/ .el-date-editor--daterange {*/
/*    padding: 3px 10px !important;*/
/*}*/

/*.taskfrom /deep/ .el-input__inner {*/
/*    border: 2px solid;*/
/*    border-color: white;*/
/*    font-size: 15px;*/
/*}*/

/*.taskfrom /deep/ .el-input__inner:focus {*/
/*    border: 2px solid;*/
/*    border-color: #409EFF*/
/*}*/

/*.taskfrom /deep/ .el-textarea__inner {*/
/*    border: 2px solid;*/
/*    border-color: white;*/
/*    padding: 0;*/
/*}*/

/*.taskfrom /deep/ .el-textarea__inner:focus {*/
/*    border: 2px solid;*/
/*    border-color: #409EFF*/
/*}*/
.flex-warp {
  flex-wrap: wrap;
}

.taskfrom /deep/ .el-form-item {
  margin-bottom: 5px;
}
</style>
